package com.eqs.enterprisequestionnaire.service;

import com.eqs.enterprisequestionnaire.model.pojo.Answer;
import com.eqs.enterprisequestionnaire.model.pojo.Option;
import com.eqs.enterprisequestionnaire.model.pojo.Question;
import com.eqs.enterprisequestionnaire.model.pojo.Response;
import com.eqs.enterprisequestionnaire.result.R;
import jakarta.annotation.Resource;
import org.apache.commons.math3.stat.StatUtils;
import org.apache.commons.math3.stat.descriptive.moment.Variance;
import org.springframework.stereotype.Service;

import java.awt.*;
import java.util.*;
import java.util.List;

import static com.eqs.enterprisequestionnaire.model.enums.QuestionEnum.LEVELQUESTION;
import static com.eqs.enterprisequestionnaire.model.enums.QuestionEnum.isChoiceType;

@Service
public class ReliabilityAnalysisService {
    @Resource
    private QuestionService questionService;
    @Resource
    private AnswerService answerService;
    @Resource
    private ResponseService responseService;
    @Resource
    private HistoryService historyService;
    @Resource
    private OptionService optionService;
    @Resource
    private CorrelationAnalysisService correlationAnalysisService;



    /*
     * 获得信度分析
     * */
    public Map<String, List<Double>> getCronbachAnalysis(Integer questionId){
        //该ID对应的题
        Question question =questionService.selectByQuestionId(questionId);
        if(!(LEVELQUESTION.getType().equalsIgnoreCase(question.getType()))) {
            return null;
        }
        //获得差异化分析Map
        Map<String,List<Double>> result = new HashMap<>();
        // 获取该问题的所有选项
        List<Option> options = historyService.getListOptionByQuestionId(questionId);
        Double Alpha=cronbachAnalysis(questionId);
        for (Option option:options) {
            Double CITCExceptOption =getCITCExceptOption(option.getId());
            Double cronbachExceptOption=getCronbachExceptOption(option.getId());
            List<Double> list = new ArrayList<>();
            list.add(CITCExceptOption);
            list.add(cronbachExceptOption);
            list.add(Alpha);
            result.put(option.getContent(),list);
        }
        return result;
    }


    /*
    * 获得Cronbach’s Alpha
    * */
    public Double cronbachAnalysis(Integer questionId){

        Double varianceTotal; //方差总
        Double totalVariance; //总方差
        Integer k;            //样本总
        //该ID对应的题
        Question question =questionService.selectByQuestionId(questionId);
        if(!(LEVELQUESTION.getType().equalsIgnoreCase(question.getType()))) {
            return null;
        }
        // 获取该问题的所有选项
        List<Option> options = historyService.getListOptionByQuestionId(questionId);

        k=options.size();
        varianceTotal=getVarianceTotal(questionId);
        totalVariance=getTotalVariance(questionId);

        Double Alpha =(k/(k-1))*(1-varianceTotal/totalVariance);

        return Alpha;
    }

    /*
     * 获得 项已删除的α系数
     * */
    public Double getCronbachExceptOption(Integer optionId){
        Double varianceTotal; //方差总
        Double totalVariance; //总方差
        Integer k;
        //该optionID对应的题
        Option option=optionService.getById(optionId);
        Question question =questionService.selectByQuestionId(option.getQuestionId());
        if(!(LEVELQUESTION.getType().equalsIgnoreCase(question.getType()))) {
            return null;
        }
        // 获取该问题的所有选项
        List<Option> options = historyService.getListOptionByQuestionId(question.getId());
        options.remove(option);

        k=options.size();
        varianceTotal=getVarianceTotal(question.getId());
        totalVariance=getTotalVariance(question.getId());

        Double Alpha =(k/(k-1))*(1-varianceTotal/totalVariance);

        return Alpha;
    }
    /*
     * 获得 校正的总计相关性(CITC)
     * */
    public Double getCITCExceptOption(Integer optionId){

        //该optionID对应的题
        Option option=optionService.getById(optionId);
        Question question =questionService.selectByQuestionId(option.getQuestionId());
        if(!(LEVELQUESTION.getType().equalsIgnoreCase(question.getType()))) {
            return null;
        }
        double[] xArray=correlationAnalysisService.optionToDouble(optionId);

        double[] yArray=new double[xArray.length];

        // 获取该问题的所有选项
        List<Option> options = historyService.getListOptionByQuestionId(question.getId());
        options.remove(option);

        double[][] yArrays=new double[options.size()][];
        int p=0;
        for (Option o:options){
            yArrays[p]= correlationAnalysisService.optionToDouble(o.getId());
            p++;
        }
        for (int i=0;i<yArrays.length;i++){
            for (int j=0;j<yArrays[i].length;j++){
                yArray[j]=yArray[j] + yArrays[i][j];
            }
        }

        return correlationAnalysisService.correlation(xArray,yArray,"1001");
    }

    public Double getVarianceTotal(Integer questionId) {
        Double varianceTotal=0.000;
        //该ID对应的题
        Question question =questionService.selectByQuestionId(questionId);
        // 获取该问题的所有选项
        List<Option> options = historyService.getListOptionByQuestionId(questionId);

        for (Option option:options){
            //根据选项ID获取该选项的所有答案(以答卷Id排序)
            List<Answer> answers =answerService.selectAllAnswer(option.getId());
            Comparator<Answer> answerComparator=Comparator.comparing(Answer::getResponseId);
            Collections.sort(answers,answerComparator);
            //Collections.sort(answers,Comparator.comparing(Answer::getResponseId));
            double[] Array=new double[answers.size()];
            int i=0;
            for (Answer answer1:answers) {
                Array[i]=answer1.getLevel();
                i++;
            }
            varianceTotal = varianceTotal + StatUtils.variance(Array);
        }
        return varianceTotal;
    }
    public Double getTotalVariance(Integer questionId) {

        //获取该问题的所有答卷(以答卷Id排序)
        List<Response> responses=responseService.selectAllResponse(
                questionService.selectByQuestionId(questionId).getQuestionnaireId());

        Comparator<Response> responseComparator = Comparator.comparing(Response::getId);
        Collections.sort(responses,responseComparator);

        //总分数组
        double[] Array=new double[responses.size()];
        int i=0;
        for (Response response:responses){
            Integer TOTAL=0;
            //查询这份答卷这道（程度）题的答案
            Answer answer=new Answer();
            answer.setResponseId(response.getId());
            answer.setQuestionId(questionId);
            List<Answer> answers =answerService.selectAll(answer);
            for (Answer a:answers) {
                TOTAL = TOTAL + a.getLevel();
            }
           Array[i]=(double) TOTAL;
            i++;
        }
        return StatUtils.variance(Array);
    }








}
